package com.xique.park.service.command.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xique.common.core.constant.HttpStatus;
import com.xique.common.core.domain.R;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.utils.command.CommandResultUtil;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.park.api.IParkConfigCommandApi;
import com.xique.park.bean.domain.ParkConfig;
import com.xique.park.constant.CommandConstant;
import com.xique.park.constant.DictConstant;
import com.xique.park.constant.ParkApiName;
import com.xique.park.service.command.service.IParkConfigCommandService;
import com.xique.system.api.RemoteSystemProjectService;
import com.xique.system.api.dto.SystemProjectDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 车场配置参数serviceImpl
 *
 * @author: xique
 */
@Service
@Slf4j
public class ParkConfigCommandServiceImpl extends CommandCommServiceImpl implements IParkConfigCommandService {

    @Autowired
    private IParkConfigCommandApi parkConfigCommandApi;

    @Autowired
    private RemoteSystemProjectService remoteSystemProjectService;

    /**
     * 单个设备下载车场配置信息
     */
    @Override
    public AjaxResult downSingleDevParkConfig(String sn, ParkConfig parkConfig) {
        JSONObject dataObj = new JSONObject();
        JSONArray ids = new JSONArray(1);
        ids.add(parkConfig.getParkId());
        dataObj.put(CommandConstant.IDS, ids);
        JSONObject dtObj = getParkDtObj(parkConfig);
        dataObj.put(CommandConstant.DT, dtObj);

        JSONObject obj = getBaseObj(parkConfig.getParkId(), sn, ParkApiName.COMMAND_SET_PARK_PARAM, ParkApiName.VER_3_0);
        obj.put(CommandConstant.DATA, dataObj);

        @SuppressWarnings("unchecked")
        Map<String, Object> params = JSONObject.toJavaObject(obj, Map.class);

        AjaxResult commandResult = parkConfigCommandApi.downParkConfig(params);
        return CommandResultUtil.handleCommandResult(commandResult, "");
    }

    /**
     * 所有设备下载车场配置信息
     */
    @Override
    public AjaxResult downParkConfig(ParkConfig parkConfig, String reminderMsg) {
        Long parkId = parkConfig.getParkId();
        if (null != parkId) {
            List<String> devCodes = getMainDeviceCodesByParkId(parkId);
            if (CollectionUtil.isNotEmpty(devCodes)) {
                boolean commandResult = true;
                StringBuilder errMsg = new StringBuilder();
                for (String devCode : devCodes) {
                    if (StringUtils.isNotEmpty(devCode)) {
                        AjaxResult result = downSingleDevParkConfig(devCode, parkConfig);
                        if (result.get(AjaxResult.CODE_TAG).equals(HttpStatus.ERROR)) {
                            commandResult = false;
                            errMsg.append(result.get(AjaxResult.MSG_TAG)).append("，");
                        }
                    }
                }
                if (commandResult) {
                    return AjaxResult.success(reminderMsg + "下发成功");
                } else {
                    return AjaxResult.commandError(reminderMsg + "下发失败，请重新下发，错误原因：" + errMsg);
                }
            } else {
                return AjaxResult.success(reminderMsg + "车场没有添加主相机，无需下发");
            }
        } else {
            return AjaxResult.commandError(reminderMsg + "下发失败，车场参数不能为空");
        }
    }

    /**
     * 车场配置实体转化为下发给设备的json格式
     */
    private JSONObject getParkDtObj(ParkConfig parkConfig) {
        JSONObject dtObj = new JSONObject();
        dtObj.put(CommandConstant.PARK_ID, parkConfig.getParkId());
        // 停车系统版本，先默认填个值
        dtObj.put(CommandConstant.MODEL, 2);
        R<SystemProjectDTO> parkInfoRes = remoteSystemProjectService.getProjectInfo(parkConfig.getParkId());
        dtObj.put(CommandConstant.STATUS, (null != parkInfoRes && null != parkInfoRes.getData()) ? parkInfoRes.getData().getStatus() : "normal");
        String config = parkConfig.getConfig();
        if (StringUtils.isNotEmpty(config)) {
            JSONObject configObj = JSONObject.parseObject(config);
            String edgeGateway = "";
            Integer payStayTime = (null != configObj.getInteger("payStayTime")) ? configObj.getInteger("payStayTime") : 15;
            Integer isDiscount = StringUtils.isNotEmpty(configObj.getString("isDiscount")) && DictConstant.YES.equals(configObj.getString("isDiscount")) ? CommandConstant.IS_DISCOUNT_Y : CommandConstant.IS_DISCOUNT_N;
            Integer broadcastDays = null != configObj.getInteger("monthBeforeDays") ? configObj.getInteger("monthBeforeDays") : 10;
            Integer renewDays = null != configObj.getInteger("monthAfterDays") ? configObj.getInteger("monthAfterDays") : 0;
            Integer isFeePolice = StringUtils.isNotEmpty(configObj.getString("isPoliceFee")) && DictConstant.YES.equals(configObj.getString("isPoliceFee")) ? CommandConstant.IS_POLICE_FEE_Y : CommandConstant.IS_POLICE_FEE_N;
            Integer enRemain = StringUtils.isNotEmpty(configObj.getString("enRemain")) && DictConstant.YES.equals(configObj.getString("enRemain")) ? CommandConstant.EN_REMAIN_YES : CommandConstant.EN_REMAIN_NO;
            String status = configObj.getString("status");
            // Integer totalSpaceCnt = 0;
            dtObj.put(CommandConstant.PAY_STAY_TIME, payStayTime);
            dtObj.put(CommandConstant.IS_DISCOUNT, isDiscount);
            dtObj.put(CommandConstant.BROADCAST_DAYS, broadcastDays);
            dtObj.put(CommandConstant.RENEW_DAYS, renewDays);
            dtObj.put(CommandConstant.IS_POLICE_FEE, isFeePolice);
            dtObj.put(CommandConstant.EDGE_GATEWAY, edgeGateway);
            dtObj.put(CommandConstant.EN_REMAIN, enRemain);
            dtObj.put(CommandConstant.STATUS, status);
        }
        return dtObj;
    }

}
